import 'package:app_core/app_core.dart';
import 'package:get/get.dart';
import 'package:yh_core_flutter_project/project/common/managers/user_manager.dart';
import 'package:yh_core_flutter_project/project/router/app_routers.dart';

/// 网络请求code=0之外的统一的错误码处理(这里msg需要toast展示还是日志打印，根据实际情况来处理)
void _handleErrorCode(int code, String? msg, {bool showErrToast = true}) {
  YHLog.e('🎯 _handleErrorCode调用: code=$code, msg=$msg');
  switch (code) {
    case 401:

      /// 401错误需要异步处理，所以单独调用
      _handle401Error();
      break;
    default:
      if (showErrToast) {
        final text = (msg?.trim().isNotEmpty ?? false) ? msg!.trim() : '请求失败～';
        YHSmartDialog.showMsg(text);
      }
  }
}

/// 处理401错误（登录过期）
Future<void> _handle401Error() async {
  await UserManager.instance.logout();
  Get.offAllNamed(AppRouters.login.r);
  YHSmartDialog.showMsg('登录已过期，请重新登录');
}

/// 为所有 BaseApi 添加 ApiService 扩展
/// 推荐使用 apiRequest、silentRequest、loadingRequest
/// 为Api添加功能，<Api extends BaseApi>: Api必须实现BaseApi接口
/// 不传入T和fromJson就是返回后台原数据
extension ApiServiceExt<Api extends BaseApi> on Api {
  Future<ApiResponse<T>> request<T>({
    Map<String, dynamic>? params,
    T Function(Map<String, dynamic>)? fromJson,
    RequestConfig? config,
    bool showLoading = true,
  }) async {
    if (showLoading) YHSmartDialog.showLoading();
    try {
      final response = await httpRequest<T>(params: params, fromJson: fromJson, config: config, onErrorCode: _handleErrorCode);
      return response;
    } catch (e) {
      return ApiResponse<T>.fromError(e, onErrorCode: _handleErrorCode);
    } finally {
      if (showLoading) YHSmartDialog.dismiss();
    }
  }

  /// 静默请求（不显示loading）
  Future<ApiResponse<T>> silentRequest<T>({Map<String, dynamic>? params, T Function(dynamic)? fromJson, RequestConfig? config}) {
    return request<T>(params: params, fromJson: fromJson, config: config, showLoading: false);
  }

  //
  // /// 显示loading的请求
  // Future<ApiResponse<T>> loadingRequest<T>({Map<String, dynamic>? params, T Function(dynamic)? fromJson, RequestConfig? config}) {
  //   return apiRequest<T>(params: params, fromJson: fromJson, config: config, showLoading: true);
  // }
}
